import React, { useState, useEffect } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Info,
  HelpCircle,
  CheckCircle,
  AlertTriangle,
  Calculator,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

const InfoTooltip = ({ children }) => (
  <TooltipProvider>
    <Tooltip>
      <TooltipTrigger asChild>
        <HelpCircle className="w-4 h-4 text-gray-400 cursor-pointer ml-1" />
      </TooltipTrigger>
      <TooltipContent>
        <p>{children}</p>
      </TooltipContent>
    </Tooltip>
  </TooltipProvider>
);

// 迪尼玛绳规格数据库 (破断拉力单位：kN)
const dyneemaRopeSpecs = [
  { diameter: 10, linearDensity: 0.071, breakingLoad: 17.8 },
  { diameter: 12, linearDensity: 0.102, breakingLoad: 25.6 },
  { diameter: 14, linearDensity: 0.14, breakingLoad: 35.1 },
  { diameter: 16, linearDensity: 0.183, breakingLoad: 46.0 },
  { diameter: 18, linearDensity: 0.232, breakingLoad: 58.2 },
  { diameter: 20, linearDensity: 0.286, breakingLoad: 71.8 },
  { diameter: 22, linearDensity: 0.346, breakingLoad: 86.9 },
  { diameter: 24, linearDensity: 0.412, breakingLoad: 103.0 },
  { diameter: 26, linearDensity: 0.483, breakingLoad: 121.3 },
  { diameter: 28, linearDensity: 0.56, breakingLoad: 140.4 },
  { diameter: 30, linearDensity: 0.642, breakingLoad: 161.0 },
];

export default function BearingCableCalculator({ crossingPoint, project }) {
  const [params, setParams] = useState({
    // 承载索基本参数
    cableDiameter: 20, // 承载索直径 (mm)
    cableWeight: 2.095, // 承载索单重 (N/m)
    cableArea: 254.47, // 承载索截面 (mm²)
    cableModulus: 30000, // 弹性模量 (MPa)
    cableBreakingLoad: 420000, // 拉断力 (N)
    spanLength: 484, // 档距 (m)

    // 导线参数
    conductorWeight: 41.67, // 导线单重 (N/m)
    conductorCount: 2, // 牵引根数

    // 工况系数
    k1Impact: 1.67, // 冲击系数(单线)
    khUnbalance: 1.2, // 不均衡系数
    k2Dynamic: 2.5, // 动载系数

    // 封网装置重量
    nettingWeight: 36.8, // 封网装置单重 (N/m)

    // 高程信息
    leftElevation: 356.9, // N3970端高程 (m)
    rightElevation: 367.7, // N3971端高程 (m)

    // 初始安全系数
    initialSafetyFactor: 200,
  });

  const [results, setResults] = useState(null);
  const [selectedRope, setSelectedRope] = useState(null);

  useEffect(() => {
    if (crossingPoint) {
      setParams((prev) => ({
        ...prev,
        spanLength: crossingPoint.spanLength || 484,
      }));
    }
  }, [crossingPoint]);

  // 计算各工况的ω值
  const calculateOmegaValues = () => {
    const omega0 = params.cableWeight; // 空载单位重量
    const omegaQ =
      omega0 +
      params.conductorCount *
        params.k1Impact *
        params.khUnbalance *
        params.conductorWeight +
      params.nettingWeight;
    const omega2 =
      omegaQ +
      params.conductorCount * params.k2Dynamic * params.conductorWeight;
    const omega3 = omegaQ + params.conductorCount * params.conductorWeight;

    return { omega0, omegaQ, omega2, omega3 };
  };

  // 状态方程求解张力（简化迭代法）
  const solveStateEquation = (omega, initialTension = 2100) => {
    const { spanLength, cableModulus, cableArea } = params;
    const h = Math.abs(params.rightElevation - params.leftElevation);
    const phi = Math.atan(h / spanLength);
    const l = spanLength / Math.cos(phi);

    let H = initialTension;
    let prevH = 0;
    let iterations = 0;
    const maxIterations = 50;
    const tolerance = 0.01;

    while (Math.abs(H - prevH) > tolerance && iterations < maxIterations) {
      prevH = H;
      const term =
        (l *
          l *
          omega *
          omega *
          cableModulus *
          cableArea *
          Math.pow(Math.cos(phi), 3)) /
        (24 * H * H);
      H = Math.sqrt(
        (l *
          l *
          omega *
          omega *
          cableModulus *
          cableArea *
          Math.pow(Math.cos(phi), 3)) /
          (24 * (term + H))
      );
      iterations++;
    }

    return H;
  };

  // 计算弧垂
  const calculateSag = (omega, tension) => {
    const { spanLength } = params;
    const h = Math.abs(params.rightElevation - params.leftElevation);
    const phi = Math.atan(h / spanLength);
    const l = spanLength / Math.cos(phi);

    return (omega * l * l) / (8 * tension * Math.cos(phi));
  };

  // 计算安全系数
  const calculateSafetyFactor = (tension) => {
    return params.cableBreakingLoad / tension;
  };

  // 执行计算
  const performCalculation = () => {
    const { omega0, omegaQ, omega2, omega3 } = calculateOmegaValues();

    // 计算各工况张力
    const H0 = params.cableBreakingLoad / params.initialSafetyFactor; // 空载张力
    const Hq = solveStateEquation(omegaQ, H0);
    const H2 = solveStateEquation(omega2, Hq);
    const H3 = solveStateEquation(omega3, Hq);

    // 计算弧垂
    const sag0 = calculateSag(omega0, H0);
    const sagQ = calculateSag(omegaQ, Hq);
    const sag2 = calculateSag(omega2, H2);
    const sag3 = calculateSag(omega3, H3);

    // 计算安全系数
    const safety0 = calculateSafetyFactor(H0);
    const safetyQ = calculateSafetyFactor(Hq);
    const safety2 = calculateSafetyFactor(H2);
    const safety3 = calculateSafetyFactor(H3);

    const calculationResults = {
      omegaValues: { omega0, omegaQ, omega2, omega3 },
      tensions: { H0, Hq, H2, H3 },
      sags: { sag0, sagQ, sag2, sag3 },
      safetyFactors: { safety0, safetyQ, safety2, safety3 },
      maxTension: Math.max(H0, Hq, H2, H3),
    };

    setResults(calculationResults);

    // 自动进行绳索选型
    performRopeSelection(calculationResults.maxTension);
  };

  // 绳索选型
  const performRopeSelection = (maxTension) => {
    const selectionSafetyFactor = 6.0; // 绳索选型安全系数
    const requiredBreakingLoad = (maxTension / 1000) * selectionSafetyFactor; // 转换为kN

    // 找到满足要求的最小规格绳索
    const suitableRopes = dyneemaRopeSpecs.filter(
      (rope) => rope.breakingLoad >= requiredBreakingLoad
    );

    if (suitableRopes.length > 0) {
      const selected = suitableRopes[0]; // 选择最小满足要求的规格
      setSelectedRope({
        ...selected,
        requiredBreakingLoad,
        actualSafetyFactor: selected.breakingLoad / (maxTension / 1000),
        selectionReason: `最大张力 ${(maxTension / 1000).toFixed(
          1
        )}kN × 安全系数 ${selectionSafetyFactor} = ${requiredBreakingLoad.toFixed(
          1
        )}kN`,
      });
    } else {
      setSelectedRope({
        error: true,
        message: `所需破断拉力 ${requiredBreakingLoad.toFixed(
          1
        )}kN 超出了现有规格范围，请考虑使用更高规格的绳索或调整设计参数。`,
      });
    }
  };

  const handleParamChange = (key, value) => {
    const numValue = parseFloat(value);
    if (!isNaN(numValue)) {
      setParams((prev) => ({
        ...prev,
        [key]: numValue,
      }));
    }
  };

  // 安全系数评估
  const getSafetyStatus = (safetyFactor, type) => {
    let minRequired;
    if (type === "static") {
      minRequired = 6.0; // 事故静载状态要求安全系数不小于6.0
    } else {
      minRequired = 4.0; // 其他状态要求安全系数不小于4.0
    }

    if (safetyFactor >= minRequired) {
      return { status: "safe", color: "text-green-600", icon: CheckCircle };
    } else {
      return { status: "danger", color: "text-red-600", icon: AlertTriangle };
    }
  };

  return (
    <div className="space-y-6">
      <Tabs defaultValue="parameters" className="w-full">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="parameters">参数设置</TabsTrigger>
          <TabsTrigger value="results">计算结果</TabsTrigger>
          <TabsTrigger value="rope-selection">绳索选型</TabsTrigger>
        </TabsList>

        {/* 参数设置标签页 */}
        <TabsContent value="parameters" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Calculator className="w-5 h-5" />
                承载索计算参数
              </CardTitle>
              <CardDescription>请根据实际工程情况设置计算参数</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                <div>
                  <Label className="flex items-center">
                    档距 (m)
                    <InfoTooltip>承载索的跨越档距</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    value={params.spanLength}
                    onChange={(e) =>
                      handleParamChange("spanLength", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    承载索直径 (mm)
                    <InfoTooltip>迪尼玛承载索的直径</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    value={params.cableDiameter}
                    onChange={(e) =>
                      handleParamChange("cableDiameter", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    承载索单重 (N/m)
                    <InfoTooltip>承载索每米的重量</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    step="0.001"
                    value={params.cableWeight}
                    onChange={(e) =>
                      handleParamChange("cableWeight", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    弹性模量 (MPa)
                    <InfoTooltip>迪尼玛绳的弹性模量</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    value={params.cableModulus}
                    onChange={(e) =>
                      handleParamChange("cableModulus", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    拉断力 (N)
                    <InfoTooltip>承载索的破断拉力</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    value={params.cableBreakingLoad}
                    onChange={(e) =>
                      handleParamChange("cableBreakingLoad", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    导线单重 (N/m)
                    <InfoTooltip>单根导线每米重量</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    step="0.01"
                    value={params.conductorWeight}
                    onChange={(e) =>
                      handleParamChange("conductorWeight", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    牵引根数
                    <InfoTooltip>同时牵引的导线根数</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    value={params.conductorCount}
                    onChange={(e) =>
                      handleParamChange("conductorCount", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    封网装置单重 (N/m)
                    <InfoTooltip>封网装置每米重量</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    step="0.1"
                    value={params.nettingWeight}
                    onChange={(e) =>
                      handleParamChange("nettingWeight", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    左端高程 (m)
                    <InfoTooltip>左侧杆塔挂点高程</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    step="0.1"
                    value={params.leftElevation}
                    onChange={(e) =>
                      handleParamChange("leftElevation", e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label className="flex items-center">
                    右端高程 (m)
                    <InfoTooltip>右侧杆塔挂点高程</InfoTooltip>
                  </Label>
                  <Input
                    type="number"
                    step="0.1"
                    value={params.rightElevation}
                    onChange={(e) =>
                      handleParamChange("rightElevation", e.target.value)
                    }
                  />
                </div>
              </div>

              <div className="pt-4">
                <Button onClick={performCalculation} className="w-full">
                  <Calculator className="w-4 h-4 mr-2" />
                  开始计算
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 计算结果标签页 */}
        <TabsContent value="results" className="space-y-4">
          {!results ? (
            <Card>
              <CardContent className="pt-6 text-center">
                <Calculator className="w-12 h-12 mx-auto mb-4 text-gray-400" />
                <p className="text-gray-600">
                  请先在"参数设置"中设置参数并点击"开始计算"
                </p>
              </CardContent>
            </Card>
          ) : (
            <Card>
              <CardHeader>
                <CardTitle>承载索四种工况计算结果</CardTitle>
                <CardDescription>
                  包含张力、弧垂、安全系数的详细计算结果
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>工况</TableHead>
                        <TableHead>单位荷载 ω (N/m)</TableHead>
                        <TableHead>张力 H (N)</TableHead>
                        <TableHead>弧垂 f (m)</TableHead>
                        <TableHead>安全系数</TableHead>
                        <TableHead>安全评估</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      <TableRow>
                        <TableCell className="font-medium">空载状态</TableCell>
                        <TableCell>
                          {results.omegaValues.omega0.toFixed(3)}
                        </TableCell>
                        <TableCell>{results.tensions.H0.toFixed(0)}</TableCell>
                        <TableCell>{results.sags.sag0.toFixed(2)}</TableCell>
                        <TableCell>
                          {results.safetyFactors.safety0.toFixed(1)}
                        </TableCell>
                        <TableCell>
                          {(() => {
                            const {
                              status,
                              color,
                              icon: Icon,
                            } = getSafetyStatus(
                              results.safetyFactors.safety0,
                              "normal"
                            );
                            return (
                              <div
                                className={`flex items-center gap-1 ${color}`}
                              >
                                <Icon className="w-4 h-4" />
                                {status === "safe" ? "安全" : "不足"}
                              </div>
                            );
                          })()}
                        </TableCell>
                      </TableRow>
                      <TableRow>
                        <TableCell className="font-medium">
                          安全放线工况
                        </TableCell>
                        <TableCell>
                          {results.omegaValues.omegaQ.toFixed(3)}
                        </TableCell>
                        <TableCell>{results.tensions.Hq.toFixed(0)}</TableCell>
                        <TableCell>{results.sags.sagQ.toFixed(2)}</TableCell>
                        <TableCell>
                          {results.safetyFactors.safetyQ.toFixed(1)}
                        </TableCell>
                        <TableCell>
                          {(() => {
                            const {
                              status,
                              color,
                              icon: Icon,
                            } = getSafetyStatus(
                              results.safetyFactors.safetyQ,
                              "normal"
                            );
                            return (
                              <div
                                className={`flex items-center gap-1 ${color}`}
                              >
                                <Icon className="w-4 h-4" />
                                {status === "safe" ? "安全" : "不足"}
                              </div>
                            );
                          })()}
                        </TableCell>
                      </TableRow>
                      <TableRow>
                        <TableCell className="font-medium">
                          事故动载状态
                        </TableCell>
                        <TableCell>
                          {results.omegaValues.omega2.toFixed(3)}
                        </TableCell>
                        <TableCell>{results.tensions.H2.toFixed(0)}</TableCell>
                        <TableCell>{results.sags.sag2.toFixed(2)}</TableCell>
                        <TableCell>
                          {results.safetyFactors.safety2.toFixed(1)}
                        </TableCell>
                        <TableCell>
                          {(() => {
                            const {
                              status,
                              color,
                              icon: Icon,
                            } = getSafetyStatus(
                              results.safetyFactors.safety2,
                              "normal"
                            );
                            return (
                              <div
                                className={`flex items-center gap-1 ${color}`}
                              >
                                <Icon className="w-4 h-4" />
                                {status === "safe" ? "安全" : "不足"}
                              </div>
                            );
                          })()}
                        </TableCell>
                      </TableRow>
                      <TableRow className="bg-red-50">
                        <TableCell className="font-medium">
                          事故静载状态
                        </TableCell>
                        <TableCell>
                          {results.omegaValues.omega3.toFixed(3)}
                        </TableCell>
                        <TableCell>{results.tensions.H3.toFixed(0)}</TableCell>
                        <TableCell>{results.sags.sag3.toFixed(2)}</TableCell>
                        <TableCell>
                          {results.safetyFactors.safety3.toFixed(1)}
                        </TableCell>
                        <TableCell>
                          {(() => {
                            const {
                              status,
                              color,
                              icon: Icon,
                            } = getSafetyStatus(
                              results.safetyFactors.safety3,
                              "static"
                            );
                            return (
                              <div
                                className={`flex items-center gap-1 ${color}`}
                              >
                                <Icon className="w-4 h-4" />
                                {status === "safe" ? "安全" : "不足"}
                              </div>
                            );
                          })()}
                        </TableCell>
                      </TableRow>
                    </TableBody>
                  </Table>
                </div>

                <div className="mt-4 p-4 bg-blue-50 rounded-lg">
                  <h4 className="font-medium mb-2">安全系数要求说明</h4>
                  <ul className="text-sm space-y-1">
                    <li>• 事故静载状态：安全系数不应小于 6.0</li>
                    <li>• 其他状态：安全系数不应小于 4.0</li>
                    <li>
                      • 最大张力：{(results.maxTension / 1000).toFixed(1)} kN
                    </li>
                  </ul>
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* 绳索选型标签页 */}
        <TabsContent value="rope-selection" className="space-y-4">
          {!selectedRope ? (
            <Card>
              <CardContent className="pt-6 text-center">
                <Info className="w-12 h-12 mx-auto mb-4 text-gray-400" />
                <p className="text-gray-600">
                  请先完成承载索计算，系统将自动进行绳索选型
                </p>
              </CardContent>
            </Card>
          ) : selectedRope.error ? (
            <Card>
              <CardContent className="pt-6">
                <Alert variant="destructive">
                  <AlertTriangle className="h-4 w-4" />
                  <AlertDescription>{selectedRope.message}</AlertDescription>
                </Alert>
              </CardContent>
            </Card>
          ) : (
            <div className="space-y-4">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <CheckCircle className="w-5 h-5 text-green-600" />
                    推荐绳索规格
                  </CardTitle>
                  <CardDescription>
                    基于计算结果自动选型的迪尼玛绳规格
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div className="text-center p-4 bg-blue-50 rounded-lg">
                      <div className="text-2xl font-bold text-blue-600">
                        Φ{selectedRope.diameter}
                      </div>
                      <div className="text-sm text-gray-600">直径 (mm)</div>
                    </div>
                    <div className="text-center p-4 bg-green-50 rounded-lg">
                      <div className="text-2xl font-bold text-green-600">
                        {selectedRope.breakingLoad}
                      </div>
                      <div className="text-sm text-gray-600">破断拉力 (kN)</div>
                    </div>
                    <div className="text-center p-4 bg-orange-50 rounded-lg">
                      <div className="text-2xl font-bold text-orange-600">
                        {selectedRope.linearDensity}
                      </div>
                      <div className="text-sm text-gray-600">线密度 (kg/m)</div>
                    </div>
                    <div className="text-center p-4 bg-purple-50 rounded-lg">
                      <div className="text-2xl font-bold text-purple-600">
                        {selectedRope.actualSafetyFactor.toFixed(1)}
                      </div>
                      <div className="text-sm text-gray-600">实际安全系数</div>
                    </div>
                  </div>

                  <div className="mt-4 p-4 bg-gray-50 rounded-lg">
                    <h4 className="font-medium mb-2">选型依据</h4>
                    <p className="text-sm text-gray-600">
                      {selectedRope.selectionReason}
                    </p>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>迪尼玛绳规格库</CardTitle>
                  <CardDescription>
                    可选的迪尼玛绳规格及其技术参数
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>直径 (mm)</TableHead>
                          <TableHead>线密度 (kg/m)</TableHead>
                          <TableHead>破断拉力 (kN)</TableHead>
                          <TableHead>选型状态</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {dyneemaRopeSpecs.map((rope) => (
                          <TableRow
                            key={rope.diameter}
                            className={
                              rope.diameter === selectedRope.diameter
                                ? "bg-green-50"
                                : ""
                            }
                          >
                            <TableCell className="font-medium">
                              Φ{rope.diameter}
                            </TableCell>
                            <TableCell>{rope.linearDensity}</TableCell>
                            <TableCell>{rope.breakingLoad}</TableCell>
                            <TableCell>
                              {rope.diameter === selectedRope.diameter ? (
                                <Badge className="bg-green-100 text-green-800">
                                  推荐选用
                                </Badge>
                              ) : rope.breakingLoad >=
                                selectedRope.requiredBreakingLoad ? (
                                <Badge
                                  variant="outline"
                                  className="text-blue-600"
                                >
                                  可选用
                                </Badge>
                              ) : (
                                <Badge
                                  variant="outline"
                                  className="text-gray-500"
                                >
                                  不满足
                                </Badge>
                              )}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}
